package site.brood.common.mybatisplus;


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

//mybatis-plus自动填充时的回调接口
@Component
public class DbMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //有表中有createTime字段时才写字段
        boolean hasSetter = metaObject.hasSetter("createTime");
        if (hasSetter) {
            //插入时写字段
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //updateTime字段中无值时，才补写入该字段
        Object val = getFieldValByName("updateTime", metaObject);
        if (val == null) {
            //更新时写字段
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }
}